﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;

namespace PS.Config.Utils
{
    public static class PropertyBagHelper
    {
        public static SPWeb ProvidedWeb = null;

        public static string GetPropertyBagValue(this string key)
        {
            string value = null;
            SPSecurity.RunWithElevatedPrivileges(() =>
            {
                if (ProvidedWeb != null)
                {
                    value = GetPropertyBagValue(key, ProvidedWeb);
                }
                else
                {
                    using (var site = new SPSite(SPContext.Current.Site.Url))
                    using (var web = site.OpenWeb())
                    {
                        value = GetPropertyBagValue(key, web);
                    }
                }
            });
            return value;
        }

        public static void SetPropertyBagValue(this string key, string value)
        {
            SPSecurity.RunWithElevatedPrivileges(() =>
            {
                if (ProvidedWeb != null)
                {
                    SetPropertyBagValue(key, value, ProvidedWeb);
                }
                else
                {
                    var web = SPContext.Current.Site.RootWeb;
                    SetPropertyBagValue(key, value, web);
                }
            });
        }

        public static string GetPropertyBagValue(this string key, SPWeb web)
        {
            string value = null;
            SPSecurity.RunWithElevatedPrivileges(() =>
            {
                if (web.Properties.ContainsKey(key))
                    value = web.Properties[key];
            });
            return value;
        }

        public static void SetPropertyBagValue(this string key, string value, SPWeb web)
        {
            SPSecurity.RunWithElevatedPrivileges(() =>
            {
                if (web.Properties.ContainsKey(key))
                    web.Properties[key] = value;
                else
                    web.Properties.Add(key, value);

                web.Properties.Update();
            });
        }
    }
}
